import React, { Component } from 'react';
import { ListItem } from './ListItem';
import { Overlay } from './Overlay';
import {connect} from 'react-redux'
import '../_css/m-layout.css'
import {ListActions} from '../_helpers/List.actions'


function parseQueryString(url){
    var str = url.split("?")[1],    //通过?得到一个数组,取?后面的参数
       items = str.split("&");    //分割成数组
    var arr,name,value;

    for(var i=0; i<items.length; i++){
     arr = items[i].split("=");    //["key0", "0"]
       name = arr[0];
        value = arr[1];
        this[name] = value;
    }
}


class List extends Component{
	this_page=null;
	total_page=null;
	url=null;
	componentDidMount() {
        this.props.dispatch(ListActions.getList('/product/?page=1&region='+this.props.region[0]+this.props.region[1]));
	}
	handleChangePage=e=>{
		this.props.dispatch(ListActions.getList('/product/?page='+e.target.getAttribute('page')+"&region="+this.props.region[0]+this.props.region[1]));

	}
	
render(){
	
	if (this.props.status==='list_success' ){
		if(this.props.list.next){
			this.url = new parseQueryString(this.props.list.next);
		this.this_page=Number(this.url.page)-1;
		this.total_page=Math.ceil(this.props.list.count/this.props.list.results.length);
		}else if(this.props.list.previous){		
			
			this.url = new parseQueryString(this.props.list.previous);
			if(this.url.page===undefined){	this.this_page=2;	}
			else{
				this.this_page=Number(this.url.page)+1;
			}
	

		}else{
			this.this_page=1;
			this.total_page=1;
		}

	}
	 if (this.props.status==='list_success')
return (
			

			
			<div>
			<div id="list">
			{this.props.list.results.map((item)=><ListItem key={item.id} {...item}/>)}
			</div>
			<div className="pagination"  >
{this.props.list.previous&&<button href="#" page={Number(this.this_page)-1<1?1:Number(this.this_page)-1} onClick={this.handleChangePage}>上一页</button>}
{this.this_page}/{this.total_page}
 {this.props.list.next&&<button href="#" page={Number(this.this_page)+1} onClick={this.handleChangePage}>下一页</button>}
			</div></div>
	
		)
		else
		return("");

}
    
}
const ConnectedList = connect((state) => {
	const {list,one, status} = state.List;
	const {region}=state.Filter;
    return {list, status,one,region};
})(List);
function Main(props, /* context */) {
	return (<div className="list"><Overlay/><ConnectedList/></div>)
}

export {Main as List};